<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								收款核销
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar :style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="所属客户" prop="customer">
									<el-select @clear="selectClear('customer')" v-model="formData.customer"
										@change="(value:any)=>selectChange(value,'customer')" multiple ref="customer"
										clearable>
										<el-option v-for="item in customerOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="customerOption[customerIndex]?.color">
													<component :is="customerOption[customerIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{customerOption[customerIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="收款单" prop="salesReceipt">
									<el-select @clear="selectClear('salesReceipt')" v-model="formData.salesReceipt"
										@change="(value:any)=>selectChange(value,'salesReceipt')" multiple ref="salesReceipt"
										clearable>
										<el-option v-for="item in salesReceiptOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="salesReceiptOption[salesReceiptIndex]?.color">
													<component :is="salesReceiptOption[salesReceiptIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{salesReceiptOption[salesReceiptIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="核销订单" prop="order">
									<el-select @clear="selectClear('order')" v-model="formData.order"
										@change="(value:any)=>selectChange(value,'order')" multiple
										ref="order" clearable>
										<el-option v-for="item in orderOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="orderOption[orderIndex]?.color">
													<component :is="orderOption[orderIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{orderOption[orderIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="订单明细" prop="orderDetail">
									<el-select @clear="selectClear('orderDetail')" v-model="formData.orderDetail"
										@change="(value:any)=>selectChange(value,'orderDetail')" multiple
										ref="orderDetail" clearable>
										<el-option v-for="item in orderDetailOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="orderDetailOption[orderDetailIndex]?.color">
													<component :is="orderDetailOption[orderDetailIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{orderDetailOption[orderDetailIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="核销金额" prop="verificationAmount">
									<el-input placeholder="请填写" type="number" v-model="formData.verificationAmount" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="核销日期" prop="verificationDate">
									<el-date-picker placeholder="请选择" style="width:100%;" v-model="formData.verificationDate"
										type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="核销人员" prop="verificationPerson">
									<el-input placeholder="请填写" readonly type="text" v-model="formData.verificationPerson" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="收款凭证" prop="receiptProof">
									<el-input type="text" clearable readonly>
										<template #prefix>
											<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
												:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
												:limit="1">
												<el-button v-if="!formData.receiptProof" text :icon="UploadFilled">
													上传图片
												</el-button>
												<el-image v-else preview-teleported style="width: 30px; height: 30px;margin: 10px auto;" :src="formData.receiptProof" :preview-src-list="[formData.receiptProof]" />
											</el-upload>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="账单明细" prop="billDetail">
									<el-select @clear="selectClear('billDetail')"
										v-model="formData.billDetail"
										@change="(value:any)=>selectChange(value,'billDetail')" multiple
										ref="billDetail" clearable>
										<el-option v-for="item in billDetailOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon
													:color="billDetailOption[billDetailIndex]?.color">
													<component
														:is="billDetailOption[billDetailIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{billDetailOption[billDetailIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="应收明细" prop="receivableDetail">
									<el-select @clear="selectClear('receivableDetail')"
										v-model="formData.receivableDetail"
										@change="(value:any)=>selectChange(value,'receivableDetail')" multiple
										ref="receivableDetail" clearable>
										<el-option v-for="item in receivableDetailOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon
													:color="receivableDetailOption[receivableDetailIndex]?.color">
													<component
														:is="receivableDetailOption[receivableDetailIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{receivableDetailOption[receivableDetailIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="收款方式" prop="paymentMethodId">
							<el-input v-model="formData.paymentMethodId" readonly type="text" clearable class="my">
								<template #prefix>
									<div>
										<el-check-tag
											:style="`color: ${paymentMethodIndex===key?'#fff':''};${paymentMethodIndex===key?`background: ${item.bg}`:''}`"
											v-for="(item,key) in paymentMethodTags" :key="key"
											:checked="paymentMethodIndex===key"
											@change="tagChange(key,'paymentMethodId')">{{item.text}}</el-check-tag>
									</div>
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="备注" prop="remark">
							<el-input type="text" v-model="formData.remark" clearable></el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import {Document,List, UserFilled, UploadFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, Plus, CircleCheckFilled, Grid } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import { formatDate } from '../../../utils/date';
	import { getShipments } from '../../../api/shipmentAPI';
	import { ElMessage, FormInstance } from 'element-plus';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		customerId: null,//所属客户
		customer: [],
		salesReceiptId: null,//核销收款单
		salesReceipt: [],
		orderId: null,//核销订单
		order: [],
		orderDetailId: null,//核销订单明细
		orderDetail: [],
		verificationAmount: null,//核销金额
		verificationDate: null,//核销日期
		verificationPerson: null,//核销人员
		receiptProof: null,//收款凭证
		files: [],
		billDetailId: null,//账单明细
		billDetail: [],
		receivableDetailId: null,//应收明细
		receivableDetail: [],
		paymentMethodId: null,//收款方式
		remark: null,//备注
	});
	//验证
	const rules = reactive({
		customer: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//所属客户
		salesReceipt: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销收款单
		order: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销订单
		orderDetail: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销订单明细
		verificationAmount: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销金额
		verificationDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销日期
		verificationPerson: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销人员
		receiptProof: [],//收款凭证
		billDetail: [],//账单明细
		receivableDetail: [],//应收明细
		paymentMethodId: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//收款方式
		remark: null,//备注
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//所有客户
	const customerOption = ref([]);
	const customerIndex = ref(-1);
	const customer = ref(null);
	//收款单
	const salesReceiptOption = ref([]);
	const salesReceiptIndex = ref(-1);
	const salesReceipt = ref(null);
	//核销订单
	const orderOption = ref([]);
	const orderIndex = ref(-1);
	const order = ref(null);
	//订单明细
	const orderDetailOption = ref([]);
	const orderDetailIndex = ref(-1);
	const orderDetail = ref(null);
	//账单明细
	const billDetailOption = ref([]);
	const billDetailIndex = ref(-1);
	const billDetail = ref(null);
	//应收明细
	const receivableDetailOption = ref([]);
	const receivableDetailIndex = ref(-1);
	const receivableDetail = ref(null);
	//收款方式
	const paymentMethodTags = ref([]);
	const paymentMethodIndex = ref(-1);
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getsaleCustomer();
				getPaymentMethod();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.verificationPerson = decodedToken?.username;
			//
			return true;
		}
		const result = await request({
			url: '/SalesReceipt/SalesReceiptById',
			params: {
				id: route.query.id
			},
		});
		console.log('SalesReceiptById --->', result);
		formData.value = result.data.t;
		selectCustomerId(result.data.t.customerId);
		//
		return true;
	}
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	//tag改变
	const tagChange = (index : number, type : string) => {
		if (type === 'paymentMethodId') {
			if (paymentMethodIndex.value === index) {
				formData.value[type] = 0;
				paymentMethodIndex.value = -1;
				return;
			}
			paymentMethodIndex.value = index;
			formData.value[type] = paymentMethodTags.value[index].value;
		}
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'customer', //哪一个下拉框，根据ref
			option: customerOption, //下拉列表选项
			indexVar: customerIndex, //当前选中项
			idVar: 'customerId', //当前id值
			blurRef: customer, //ref
			fun: selectCustomerId
		}, {
			type: 'salesReceipt', //哪一个下拉框，根据ref
			option: salesReceiptOption, //下拉列表选项
			indexVar: salesReceiptIndex, //当前选中项
			idVar: 'salesReceiptId', //当前id值
			blurRef: salesReceipt, //ref
		}, {
			type: 'order', //哪一个下拉框，根据ref
			option: orderOption, //下拉列表选项
			indexVar: orderIndex, //当前选中项
			idVar: 'orderId', //当前id值
			blurRef: order, //ref
		}, {
			type: 'orderDetail', //哪一个下拉框，根据ref
			option: orderDetailOption, //下拉列表选项
			indexVar: orderDetailIndex, //当前选中项
			idVar: 'orderDetailId', //当前id值
			blurRef: orderDetail, //ref
		}, {
			type: 'billDetail', //哪一个下拉框，根据ref
			option: billDetailOption, //下拉列表选项
			indexVar: billDetailIndex, //当前选中项
			idVar: 'billDetailId', //当前id值
			blurRef: billDetail, //ref
		}, {
			type: 'receivableDetail', //哪一个下拉框，根据ref
			option: receivableDetailOption, //下拉列表选项
			indexVar: receivableDetailIndex, //当前选中项
			idVar: 'receivableDetailId', //当前id值
			blurRef: receivableDetail, //ref
		}];
		//
		handSelectChange(formData, typeList, value, type, key);
	}

	const selectCustomerId = async (customerId : number) => {
		const result = await request({
			url: '/SalesReceipt/selectSalesOrder',
			params: { customerId }
		});		//
		console.log('selectCustomerId --->', result);

		//收款单
		salesReceiptOption.value = [];
		result.data.t.receipts.forEach((item : any, key : number) => {
			salesReceiptOption.value.push({
				label: `${item.saleCustomer.customerName}_${item.amountReceived}元_${formatDate(item.receivingDate)}`,
				value: item.receiptId,
				icon: Plus,
				color: '#42b33e'
			});
			if (formData.value.salesReceiptId === item.receiptId) {
				formData.value.salesReceipt = [item.receiptId];
				salesReceiptIndex.value = key;
			}
		});

		//核销订单
		orderOption.value = [];
		result.data.t.salesOrders.forEach((item : any, key : number) => {
			orderOption.value.push({
				label: `${item.orderNumber}_${item.dictData.dictLabel}_${item.totalProfit}元 | ${(item.customer.customerName)}`,
				value: item.orderId,
				icon: CircleCheckFilled,
				color: '#fa9e00'
			});
			if (formData.value.orderId === item.orderId) {
				formData.value.order = [item.orderId];
				orderIndex.value = key;
			}
			//订单明细
			orderDetailOption.value = [];
			item.orderDetail.forEach((item1 : any, key1 : number) => {
				orderDetailOption.value.push({
					label: `${item.orderNumber}_${item1.products.productName}${item1.products.model}`,
					value: item1.orderDetailId,
					icon: Document,
					color: '#82b51b'
				});
				if (formData.value.orderDetailId === item1.orderDetailId) {
					formData.value.orderDetail = [item1.orderDetailId];
					orderDetailIndex.value = key1;
				}
			});
		});
		//账单明细
		billDetailOption.value = [];
		result.data.t.customerStatements.forEach((item : any, key : number) => {
			item.customerStatementDetails.forEach((item1 : any, key1) => {
				billDetailOption.value.push({
					label: `${item.billNumber}`,
					value: item1.billDetailId,
					icon: Grid,
					color: '#60b33e'
				});
				if (formData.value.billDetailId === item1.billDetailId) {
					formData.value.billDetail = [item1.billDetailId];
					billDetailIndex.value = key1;
				}
			});
		});
		//应收明细
		receivableDetailOption.value = [];
		result.data.t.payableDetails.forEach((item : any, key : number) => {
			receivableDetailOption.value.push({
				label: `${item.dictData[1].dictLabel}_${formatDate(item.occurrenceDate)}`,
				value: item.receivableDetailId,
				icon: List,
				color: '#5283ff'
			});
			if (formData.value.receivableDetailId === item.receivableDetailId) {
				formData.value.receivableDetail = [item.receivableDetailId];
				receivableDetailIndex.value = key;
			}
		});
	}

	//获取所有客户
	const getsaleCustomer = async () => {
		const result = await request({
			url: '/SalesReceipt/selectCustomer',
		});
		//
		console.log('getsaleCustomer --->', result);
		//
		customerOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			customerOption.value.push({
				label: `${item.customerName}（${item.customerRating}）${item.billingMethod}`,
				value: item.customerId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.customerId === item.customerId) {
				formData.value.customer = [item.customerId];
				customerIndex.value = key;
				selectCustomerId(item.customerId);
			}
		});
	}
	//获取收款方式
	const getPaymentMethod = async () => {
		const data = await getShipments('payment_method', 'tag');
		paymentMethodTags.value = [];
		data.forEach((item : any, key : number) => {
			paymentMethodTags.value.push(item);
			//
			if (formData.value.paymentMethodId === item.value) {
				paymentMethodIndex.value = key;
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.billDetail;
				delete data.order;
				delete data.orderDetail;
				delete data.receivableDetail;
				delete data.salesReceipt;
				delete data.customer;
				let type = '';
				if (!route.query.id) {
					type = '/saveSalesReceipt';
				} else {
					type = '/updateSalesReceipt';
				}
				//
				const result = await request({
					url: '/SalesReceipt' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//凭证上传成功
	const onSuccess = (res : any) => {
		console.log('onSuccess --->', res);
		//
		formData.value.receiptProof = res.t;
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}
	.el-upload-list--text {
		display: none;
	}
	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>